package xj.graph2d.template.uml;

import xj.graph2d.DrawShape;
import xj.graph2d.DrawShapeConstants;
import xj.graph2d.GraphEdgeBase;
import xj.graph2d.Label;
import xj.graph2d.template.UMLActivityDiagramTemplate;
import xj.graph2d.template.UMLTemplate;
import xj.model.uml.ActivityFlow;

public class UMLActivityFlowModelListener extends UMLAbstractModelListener {

  public UMLActivityFlowModelListener() {
  }

  public UMLActivityFlowModelListener(UMLTemplate template) {
    this(null, null, template);
  }

  public UMLActivityFlowModelListener(Object model, DrawShape shape,
      UMLTemplate template) {
    super(model, shape, template);
  }

  @Override
  public void updateModel() {
    if (shape instanceof GraphEdgeBase && model instanceof ActivityFlow) {
      GraphEdgeBase edge = (GraphEdgeBase) shape;
      ActivityFlow tmodel = (ActivityFlow) model;
      String label = edge.getLabel(DrawShapeConstants.ROLE_EDGE_LABEL);
      String cond = null;
      if (label != null) {
	int i, j;
	i = label.indexOf('[');
	if (i >= 0) {
	  j = label.indexOf(']', i);
	  if (j > i) {
	    cond = label.substring(i + 1, j).trim();
	  } else {
	    cond = label.substring(i + 1).trim();
	  }
	} else {
	  cond = label;
	}
	tmodel.setCondition(cond);
      }
    }
  }

  @Override
  public void updateShape() {
    if (shape instanceof GraphEdgeBase && model instanceof ActivityFlow) {
      GraphEdgeBase edge = (GraphEdgeBase) shape;
      ActivityFlow tmodel = (ActivityFlow) model;
      String cond = tmodel.getCondition();
      if (cond != null) {
	String label = ("[" + cond + "]");
	Label lshape = setLabel(edge, DrawShapeConstants.ROLE_EDGE_LABEL,
	    label, "condition", true, UMLActivityDiagramTemplate.FLOW_FONT,
	    UMLActivityDiagramTemplate.FLOW_COLOR);
	if (lshape != null) {
	  lshape.setDisplayName("Condition");
	}
      }
    }
  }

}
